<template>
    <div class="search-rd">
        <my-dialog v-model="msgshow"  type="alert" :text="msgtext"></my-dialog>
        <my-loading :show="lodingShow"></my-loading>
        <div class="search_head" :style="{height: !isSearching === true ? '95px' : '55px'}">
            <div class="search_form" :class="{hidden: touchDirect}">
                <div class="search-main">
                    <a class="search_back search_btn" @click="back"><i></i></a>
                    <div class="search_input">
                       <i class="search_icon"></i>
                        <input type="text" v-model.trim="query" placeholder="输入搜索关键字" name="keyWord" id="keyWord" ref="queryInput" @click="isSearching = true">
                    </div>
                    <a href="javascript:;" class="search_btn" @click="searchSubmit">搜索</a>
                </div>

                <div class="prod-conditions box-row top-1px bottom-1px" v-show="!isSearching">
                    <a href="javascript:;" class="flex-1" :style="{color:searchQuery.mix === true ? '#ff463c' : searchQuery.saleDesc === false ? '#333' : '#333'}" @click="changeQuery('mix')">
                        综合
                    </a>
                    <a href="javascript:;" class="flex-1" :class="[searchQuery.saleDesc === true ? 'down active' : searchQuery.saleDesc === false ? 'up active' : '']" @click="changeQuery('saleDesc')">
                        <span>
                            销量
                            <i class="triangle-up"></i>
                            <i class="triangle-down"></i>
                        </span>
                    </a>
                    <a href="javascript:;" class="flex-1" :class="[searchQuery.priceDesc === true ? 'down active' : searchQuery.priceDesc === false ? 'up active' : '']" @click="changeQuery('priceDesc')">
                        <span>
                            价格
                            <i class="triangle-up"></i>
                            <i class="triangle-down"></i>
                        </span>
                    </a>
                </div>
            </div>
        </div>
        <div class="searchTagBox" v-show="isSearching">
            <div class="searchHistory tagList" v-show="hasHistory">
                <div class="searchTop">
                    <span>搜索历史</span>
                    <i class="trash" @click="removeHistory"></i>
                </div>
                <ul>
                    <li class="searchTag" v-for="tag in localHistory" v-text="tag" @click="tagSearch(tag)"></li>
                </ul>
            </div>
            <div class="hotSearch tagList">
                <div class="searchTop">
                    <span>热搜</span>
                </div>
                <ul>
                    <li class="searchTag" v-for="tag in moreData" v-text="tag.name" @click="tagSearch(tag.name)"></li>
                </ul>
            </div>
        </div>
        <div class="prod-list" v-show="!isSearching">
            <div class="empty-img" v-show="prodDatas.length == 0">
                <img src="~__assets/images/empty.png" alt="">
                <p>抱歉！暂无相关产品</p>
            </div>
            <ul class="prod-box">
                <li v-for="(data,index) in prodDatas" :key="index">
                    <a href="javascript:;" @click="prodDeatil(data.id)">
                        <div class="moreProdLoadImg">
                            <img :src="data.image[0]" class="prod-img">
                        </div>
                        <span class="prod-name" v-text="data.product_name"></span>
                        <p class="prod-price">
                            <span class="now-price">￥<span class="big-price"  v-text="data.big_price"></span><span class="small-price" v-if="data.small_price">.{{data.small_price}}</span>
                            </span>
                        </p>
                    </a>
                </li>
                <my-spinner :isLoading="isLoading" :allLoaded="allLoaded"></my-spinner>
            </ul>
        </div>
    </div>
</template>
<style scoped lang="scss">
    .search-rd{
        width:100%;
        height:100%;
        background-color: #fff;
        .search_head{
            height: 55px;
            position: relative;
            z-index: 100;
            background-color: #fff;
        }
        .search_form {
            background-color: #fff;
            overflow: hidden;
            -webkit-transition: -webkit-transform .5s ease;
            transition: transform .5s ease;
            position: fixed;
            top:0;
            width:100%;
            &.hidden{
                transform: translate3d(0px, -55px, 0px);
            }

            .prod-conditions{
                width:100%;
                font-size: 14px;
                position: relative;
                @include lineHeight(40px,40px);
                text-align: center;

                a{
                    font-size: 14px;
                    &.active{color:$activeColor;}
                    &.up{
                        .triangle-up{
                            border-bottom-color:#ff463c;
                        }
                    }
                    &.down{
                        .triangle-down{
                            border-top-color:#ff463c;
                        }
                    }
                    span{
                        position: relative;
                        display: inline-block;
                        padding-right:15px;
                        height:100%;

                        .triangle-up{
                            @include triangle(4px);
                            position: absolute;
                            top:10px;
                            right:0;
                            margin-left:2px;
                        }
                        .triangle-down{
                            @include triangle(4px,bottom);
                            position: absolute;
                            top:22px;
                            right:0;
                        }
                    }
                    
                    // &.up{
                    //     .triangle{
                    //         @include triangle(5px,top,#ff463c);
                    //         margin-left:2px;
                    //         vertical-align: 2px;
                    //     }
                    // }

                    
                }

                &.top-1px::before{
                    position: absolute;
                    right: 0;
                    bottom: 0;
                    left: 0;
                    height: 1px;
                    content: '';
                    background-color: #e5e5e5;
                    -webkit-transform: scaleY(0.5);
                    transform: scaleY(0.5);
                }
                &.bottom-1px::after{
                    background-color: #e5e5e5;
                }
            }

            .search-main{
                height:a(110px);
                padding:a(20px) 0;
                .search_btn {
                    font-size: 14px;
                    width: 16%;
                    float: left;
                    height:35px;
                    line-height: 35px;
                    text-align: center;
                    color: #000;
                }
                
                .search_back{
                    display: inline-block;
                    width:10%;
                    padding-top: 5px;
                    i{
                        display: inline-block;
                        width:20px;
                        height:20px;
                        background: url(~__assets/images/icon/search-back.png) no-repeat;
                        background-size: 100% 100%;
                    }
                }

                .search_input {
                    position: relative;
                    float: left;
                    width: 74%;

                    .search_icon{
                        position: absolute;
                        left: 10px;
                        top: 10px;
                        width: 15px;
                        height: 15px;
                        display: inline-block;
                        background: url('~__assets/images/icon/search1.png') no-repeat;
                        background-size: 100% 100%;
                    }
                }

                input{
                    font-size: 14px;
                    width:100%;
                    -webkit-box-sizing: border-box;
                    box-sizing: border-box;
                    height: 35px;
                    /*text-align: center;*/
                    padding-left: 35px;
                    border: 0;
                    border-radius: 25px;
                    background-color: #f7f7f7;
                }
            }
        }

        .searchTagBox{
            padding-bottom:20px;

            .searchTag{
                float:left;
                height: 24px;
                line-height: 24px;
                padding-left: 13px;
                padding-right: 13px;
                border-radius: 3px;
                margin-right: 5px;
                margin-top:5px;
                background-color: #f0f2f5;
                color: #686868;
            }

            .tagList{
                overflow: hidden;
                padding:10px;
            }

            .searchTop{
                position: relative;
                height:20px;
            }
            .trash{
                position: absolute;
                background: url('~__assets/images/icon/trash.png') no-repeat;
                background-size: 100% 100%;
                display: inline-block;
                right:10px;
                width:18px;
                height:18px;
            }

            .searchResultBox .tab_nav{
                height:40px;
                /*line-height: 40px;*/
                background-color: #fff;
            }
        }

        .prod-box{overflow: hidden;}
        .wrapper{height:100%;}
        .prod-list{
            padding:10px 0.266667rem;
            .empty-img {
                padding:100px 0;
                img{
                    display: block;
                    margin: 0 auto;
                    width: a(240px);
                }
                p{
                    margin-top:30px;
                    font-size: 16px;
                    text-align: center;
                    color:#9e9e9e;
                }
            }

        }
        .prod-box li{
            float: left;
            max-width: 50%;
            display: inline-block;
            width: 4.5rem;
            padding-bottom: 4px;
            position: relative;
            &:nth-child(even) {
                float:right;
            }

            // &:nth-child(even) {
            //     padding-left: 3px;
            // }
            .prod-img{
                width:100%;
                height:a(370px);
                border-radius: 10px;
            }
            .prod-name{
                display: inline-block;
                height: 33px;
                width:100%;
                font-size: 13px;
                overflow: hidden;
                -o-text-overflow: ellipsis;
                text-overflow: ellipsis;
                -webkit-line-clamp: 2;
                -webkit-box-orient: vertical;
                word-break: break-word;
                color: #232326;
                margin-top: 5px;
                line-height: 17px;
                margin-bottom: 3px;
                padding: 0 4px;
            }
            .prod-price{
                height: 23px;
                font-size: 13px;
                overflow: hidden;
                .now-price{
                    color: #f23030;
                    display: inline-block;
                    padding: 0 5px 0 4px;
                    position: relative;
                    top: 1px;
                    height: 25px;
                    line-height: 25px;
                    .big-price{font-size: 16px;}
                    .small-price{font-size: 12px;}
                }
            }
        }
    }
</style>
<script>
    
    import mySpinner from '__cp/mySpinner'
    import {getProductList} from '__api'
    export default{
        name:'search-view',
        components:{ mySpinner},
        data(){
            return{
                searchQuery:{
                    page:1,
                    mix:true,
                    saleDesc:'unclick',
                    priceDesc:'unclick'
                },
                scrollData:0,
                touchDirect:false,
                allLoaded: false,
                isLoading:false,
                query:'',
                localHistory:[],
                hasHistory:false,
                isSearching:true,
                count:0,
                currntIndex:1,
                prodDatas:[],
                moreData:[
                    {name:"热搜1"},
                    {name:"热搜2"},
                    {name:"热搜3"},
                    {name:"热搜4"},
                ],
                msgshow:false,
                msgtext:'',
                lodingShow:false
            }
        },
        watch:{
            isSearching:function(newValue){
                if(!newValue){
                    // 此处体验不大好，暂不使用防抖
                    //window.addEventListener('scroll', this.debouce(),false);

                    window.addEventListener('scroll', this.myScroll,false);
                } else {
                    window.removeEventListener('scroll', this.myScroll,false);
                }
            },
        },
        mounted:function(){
            this.$nextTick(function () {
                this.getLocalHistory();
            })
        },
        destroyed(){
            window.removeEventListener('scroll', this.myScroll,false);
        },
        methods:{
            changeQuery(param){
                if(param == 'page'){

                } else {    //#todo 乱的一匹
                    this.searchQuery.page = 1;
                    Object.keys(this.searchQuery).forEach((item)=>{
                        if(item != 'page' && param != 'mix'){
                            if(item == param){
                                this.searchQuery[item] === true ? this.searchQuery[item] = false : this.searchQuery[item] === false ? this.searchQuery[item] = true : this.searchQuery[item] = false;
                            } else {
                                this.searchQuery[item] = 'unclick'
                            }
                            this.searchQuery['mix'] = false;
                        } else if(item == param && param == 'mix'){
                            this.searchQuery[item] = true;
                        } else {
                            this.searchQuery[item] = 'unclick'
                        }
                    })
                    this.searchQuery['page'] = 1;
                }
                this.toTop();
                this.getData(true);
            },
            myScroll () {
                this.calcDirect();
                if(this.getScrollTop() + this.getWindowHeight() + 150 > this.getScrollHeight()){
                    if(this.allLoaded || this.isLoading){
                      return;
                    }
                    this.getData();
                }
            },
            calcDirect(){
                if(this.getScrollTop() > 55 && this.getScrollTop() - this.scrollData > 0){
                    this.touchDirect = true;
                } else {
                    this.touchDirect = false;
                }
                this.scrollData = this.getScrollTop();
            },
            debouce(){  // 此处体验不大好，暂不使用防抖
                let timer = null,
                    delay = 100;

                return ()=>{
                    if(timer) clearTimeout(timer);
                    timer = setTimeout(()=>{
                        this.myScroll();
                    },delay);
                    
                }
            },
            getScrollTop(){
            　　let scrollTop = 0, bodyScrollTop = 0, documentScrollTop = 0;
            　　if(document.body){
            　　　　bodyScrollTop = document.body.scrollTop;
            　　}
            　　if(document.documentElement){
            　　　　documentScrollTop = document.documentElement.scrollTop;
            　　}
            　　scrollTop = (bodyScrollTop - documentScrollTop > 0) ? bodyScrollTop : documentScrollTop;
            　　return scrollTop;
            },
            getScrollHeight(){
            　　let scrollHeight = 0, bodyScrollHeight = 0, documentScrollHeight = 0;
            　　if(document.body){
            　　　　bodyScrollHeight = document.body.scrollHeight;
            　　}
            　　if(document.documentElement){
            　　　　documentScrollHeight = document.documentElement.scrollHeight;
            　　}
            　　scrollHeight = (bodyScrollHeight - documentScrollHeight > 0) ? bodyScrollHeight : documentScrollHeight;
            　　return scrollHeight;
            },
            getWindowHeight(){
            　　let windowHeight = 0;
            　　if(document.compatMode == "CSS1Compat"){
            　　　　windowHeight = document.documentElement.clientHeight;
            　　}else{
            　　　　windowHeight = document.body.clientHeight;
            　　}
            　　return windowHeight;
            },
            searchSubmit(){
                if(this.$refs.queryInput.value == ''){
                    console.log('点击了按钮')

                    this.msgshow = true;
                    this.msgtext = '关键词不能为空'
                    // this.$set(this.toast,'show',true)
                    // this.$set(this.toast,'text','关键词不能为空')

                    return 
                }

                this.query = this.$refs.queryInput.value;
                
                let hadKeyWord = false;
                this.localHistory.forEach((obj,index)=>{
                    if(this.$refs.queryInput.value == obj){
                        hadKeyWord = true;
                    }
                });

                if(!hadKeyWord){

                    this.localHistory.unshift(this.$refs.queryInput.value)
                    if(this.localHistory.length > 20){
                        this.localHistory.length = 20;
                    }

                    if(window.localStorage){
                        localStorage.setItem('productQueryHistory',JSON.stringify(this.localHistory));
                    }
                }
                
                this.getData(true);
                this.isSearching = false;
            },
            getData:function(isChange){

                if(this.isLoading) return;
                if(isChange){
                    this.allLoaded = false;
                }

                this.isLoading = true;

                getProductList({
                    page:this.searchQuery.page,
                    name:this.query,
                    mix:this.searchQuery.mix,
                    saleDesc:this.searchQuery.saleDesc,
                    priceDesc:this.searchQuery.priceDesc
                }).then( res => {
                        if(isChange){
                            this.prodDatas = [];
                        }

                        if(res.errno == -1){
                            // 查询错误
                            this.isLoading = false;
                            this.allLoaded = true;

                            this.msgshow = true;
                            this.msgtext = res.msg;

                            return;
                        }

                        if(res.errno == 2){
                            // 已经最后一页 || 无数据
                            this.allLoaded = true;
                            this.isLoading = false;
                            return;
                        }

                        if(res.errno == 401){
                            // 未登录
                            this.isLoading = false;
                            this.allLoaded = true;

                            this.msgshow = true;
                            this.msgtext = res.msg;

                            setTimeout(()=>{
                                this.$router.push({path:'/login'})
                            } ,700)
                            
                            return;
                        }

                        res.forEach((item)=>{
                            item.image = item.image.split(',');
                            let a =  item.price.toString().split('.');
                            item.big_price = a[0];
                            item.small_price = a[1];
                        })

                        this.prodDatas = this.prodDatas.concat(res);

                        if(res.length < 10){
                            this.allLoaded = true;
                            this.isLoading = false;
                        } else {
                            this.searchQuery.page++;
                            this.isLoading = false;
                        } 
                })
            },
            toTop(){
                this.touchDirect = false;
                document.body.scrollTop = 0;
                document.documentElement.scrollTop = 0;
            },
            tagSearch(name){
                this.$refs.queryInput.value = name;
                this.query = name;
                this.isSearching = false;

                this.getData(true);
            },
            getLocalHistory(){
                if(window.localStorage && JSON.parse(localStorage.getItem('productQueryHistory')))
                {
                    this.localHistory = JSON.parse(localStorage.getItem('productQueryHistory'))
                    this.hasHistory = true
                }else{
                    this.hasHistory = false
                    this.localHistory = []
                }
            },
            removeHistory(){
                if(window.localStorage) localStorage.removeItem('productQueryHistory')
                this.getLocalHistory();                
            },
            back(){
                if (window.history.length <= 1) {
                    this.$router.push({path:'/index'})
                    return false
                } else {
                    this.$router.go(-1)
                }
                //上面都没执行就说明卡在当前页不是最后一条， histroy记录数量大于1，又没有回退记录，只能返回首页，
                //如果上面都执行了 页面都跳走了，这个也就不用管了   
                setTimeout(() => {
                    this.$router.push({path:'/'})      
                },500)
            }
        }
    }

</script>
